package com.springboot.common.lock.impl;

import com.springboot.common.lock.Lock;
import com.springboot.common.lock.LockFactory;
import com.springboot.common.util.StringUtil;
import org.apache.curator.framework.CuratorFramework;

/**
 * zk锁工厂实现类
 *
 * @author supu
 * @date 2019-03-22 11:38
 **/
public class ZookeeperLockFactory implements LockFactory {

    private CuratorFramework curatorFramework;
    private String projectName;

    public ZookeeperLockFactory(CuratorFramework curatorFramework, String projectName) {
        this.curatorFramework = curatorFramework;
        this.projectName = StringUtil.isEmpty(projectName) ? "/default" : projectName;
    }

    public static Build builder() {
        return new Build();
    }

    @Override
    public Lock getLock(String path) {
        return new SimpleZookeeperLock(concatPath(path), curatorFramework);
    }

    private String concatPath(String path){
        return projectName.concat(path.startsWith("/") ? path : "/".concat(path));
    }

    public static class Build {
        private CuratorFramework curatorFramework;

        private String projectName;

        public Build setCuratorFramework(CuratorFramework curatorFramework) {
            this.curatorFramework = curatorFramework;
            return this;
        }

        public Build setProjectName(String projectName) {
            this.projectName = projectName;
           return this;
        }

        public ZookeeperLockFactory build() {
            return new ZookeeperLockFactory(curatorFramework, projectName);
        }
    }
}
